<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      canvas {
        border: 1px solid;
      }
    </style>
  </head>

  <body>
    <canvas id="myid" width="500" height="500"></canvas>
    <script>
      function drawImageFn(imgEle) {
        // 获取canvas画布
        let canvas = document.querySelector("#myid");
        // 获取画布里的画笔,上下文
        let ctx = canvas.getContext("2d");
        // 把对象绘制到画布上
        ctx.drawImage(imgEle, 0, 0);
      }

      function loadImg(src, cb) {
        return new Promise((resolve, reject) => {
          let imgEle = document.createElement("img");
          imgEle.src = src;
          imgEle.onload = function () {
            console.log("图片加载完毕");
            cb && cb(imgEle);
            resolve(imgEle);
          };

          imgEle.onerror = function () {
            reject("图片加载失败");
          };
        });
      }

      let strurl =
        "https://img0.baidu.com/it/u=3595884318,1137719294&fm=253&fmt=auto&app=138&f=JPEG?w=663&h=500";

      loadImg(strurl).then(
        (res) => {
          drawImageFn(res);
        },
        (err) => {
          console.log(err);
        }
      );
    </script>
  </body>
</html>
